<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条区域 -->

      <el-steps :active="active-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- form表单  -->
      <el-form
        ref="addFormRef"
        :rules="addFormRules"
        :model="addForm"
        label-width="80px"
        label-position="top"
      >
        <!-- tab区域 -->
        <el-tabs
          tab-position="left"
          v-model="active"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <!-- 商品价格 -->
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <!-- 商品重量 -->
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <!-- 商品数量 -->
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <!-- 分类 级联选择器 -->
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级连选择器 -->
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <!-- 多选框按钮组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" v-for="(cb,i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片上传 -->
            <el-upload
              :action="URL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers=headers
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
              <!-- 富文本编辑器组建 -->
              <quill-editor v-model="addForm.goods_introduce"></quill-editor>
              <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
          <el-tab-pane label="完成" name="5">完成</el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 图片预览弹窗 -->


      <el-dialog
  title="图片预览"
  :visible.sync="preImgdialogVisible"
  width="50%">
  <!-- <span>这是一段信息</span> -->
  <img :src="imgURL" />
  
</el-dialog>
    </el-card>
  </div>
</template>
           
<script>
import _ from 'loadsh';
export default {
  data() {
    return {
    preImgdialogVisible:false,
    imgURL:'',
      active: '0',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics:[],
        goods_introduce:'',
        attrs:[]
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      //   分类数据
      cateList: [],
      //   级连选择器相关信息
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
        //   选中的分类的商品的分类数组
      },
      manyTableData: [],
      onlyTableData: [],
      URL:'http://127.0.0.1:8888/api/private/v1/upload',
      headers:{
          Authorization:window.sessionStorage.getItem('token')
      }
    };
  },
  methods: {
    async getCateList() {
      let { data: res } = await this.axios.get('categories');
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('请求分类数据错误');
      }
      this.cateList = res.data;
    },
    //   级连选择器触发的动作
    handleChange() {
      //   判断选中的数组的长度是否为3
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },
    beforeTabLeave(activeName, oldActiveName) {
      //   console.log('即将离开的标签页的名称是'+oldActiveName);
      //    console.log('即将进入的标签页的名称是'+activeName);
      // return false 则可以阻止跳转
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.info('请选择商品分类');
        return false;
      }
    },
    async tabClicked() {
      //   console.log(this.active);
      if (this.active == '1') {
        // 说明是进入了商品参数 动态属性
        let { data: res } = await this.axios.get(
          `categories/${this.addForm.goods_cat[2]}/attributes`,
          {
            params: {
              sel: 'many'
            }
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error('获取数据失败');
        }
        // console.log(res);
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length == 0 ? [] : item.attr_vals.split(' ');
        });
        this.manyTableData = res.data;
      } else if (this.active == '2') {
        let { data: res } = await this.axios.get(
          `categories/${this.addForm.goods_cat[2]}/attributes`,
          {
            params: {
              sel: 'only'
            }
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error('获取数据失败');
        }
        // console.log(res);

        this.onlyTableData = res.data;
      }
    },
    // 图片上传和移除
     handleRemove(file, fileList) {
        console.log(file, fileList);
        const filepath=file.response.data.tmp_path;
       const index= this.addForm.pics.findIndex(item=>{
           return  item.pic=filepath
        })
        // 从本地数组删除该图片信息
        this.addForm.pics.splice(index,1);
      },
      handlePreview(file) {
        console.log(file);
        // 路径是 file.response.data.url
        this.imgURL=file.response.data.url
        this.preImgdialogVisible=true;
      },
    //   监听上传成功的钩子函数事件
    handleSuccess(response, file, fileList){
        console.log(response);
        // response是长传成功的返回值 判断是否上传成功
        const picInfo={
            pic:response.data.tmp_path
        }
        this.addForm.pics.push(picInfo)
        // console.log(this.addForm,999);
    },
    add(){
        this.$refs.addFormRef.validate(async valid=>{
            if(!valid){
                return this.$message.error('请填写必要的信息')
            }
            // 开始提交数据到后台
            const form=_.cloneDeep(this.addForm);
            form.goods_cat=form.goods_cat.join(',');
            // 处理动态参数
            this.manyTableData.forEach(item=>{
                const newInfo={attr_id:item.attr_id,attr_value:item.attr_vals.join(' ')};
                this.addForm.attrs.push(newInfo)
            })
             this.onlyTableData.forEach(item=>{
                const newInfo={attr_id:item.attr_id,attr_value:item.attr_vals};
                this.addForm.attrs.push(newInfo)
            })
            form.attrs=this.addForm.attrs;

            let {data:res}=await this.axios.post('goods',form)
            console.log(res);
            if(res.meta.status!==201) {
                return this.$message.error('提交出错')
            }
            this.$message.success('提交成功')
            this.$router.push('/goods')
            

        })
    }
  },
  mounted() {
    this.getCateList();
  }
};
</script>
<style scoped lang="less">
.el-card {
  margin-top: 15px;

}
.el-checkbox {
  margin: 0 5px;
}
img{
    width:100%;
    height: 100%;
}
.el-button {
    margin-top:90px;
}
</style>